# -*- coding: utf-8 -*-
# @Time : 2022/3/22 9:24
# @FileName: Fund.py
# @Mail: lizhigen1996@aliyun.com

__author__ = 'Zhigen.li'

from Config.Config import config
from UI.Table.FundMainWin import Ui_FundMainWin
import sys
import time
import atexit
import webbrowser
from PyQt5.QtCore import Qt, QFile, QIODevice, QUrl
from PyQt5.QtGui import QIcon, QFont
from PyQt5.QtWidgets import QApplication, QStyleFactory, QMessageBox
from res.resource_tool import ReBuildResources
from Tools.DBTool import DBSession
from UI.Util.UpgradeMessage import UpgradeMessage
from UI.Login.LoginDialog import LoginDialog
from UI.LoadWidget import LoadWidget
from Tools import fcntlock as fcntl
import requests
from res import resource_rc

# Config
import os
import json
from datetime import datetime
from functools import wraps
from PyQt5.QtWidgets import QMessageBox
from Tools.DBTool import DBSession

# DBTool
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, UniqueConstraint, Index, Boolean
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, close_all_sessions
from datetime import datetime
import pymysql
import socket
import uuid
from datetime import datetime

# fcnlock
import os
from win32con import LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY
from pywintypes import OVERLAPPED
from win32file import _get_osfhandle, LockFileEx, UnlockFileEx

#Util
import os
import re
import time
import requests
from json import loads
from datetime import datetime
from urllib.request import urlopen, Request, urlcleanup
from bs4 import BeautifulSoup
from win32comext.shell import shell
import os
import pythoncom
from Config.Config import config

# AccurateWidget
import os
import sys
import time
from datetime import datetime
from threading import Thread, RLock
from PyQt5.QtCore import Qt, QPoint, pyqtSignal
from PyQt5.QtGui import QGuiApplication, QKeyEvent, QPainter, QPixmap, QCursor, QIcon
from PyQt5.QtWidgets import QWidget, QGridLayout, QApplication, QLabel, QMenu, QAction, QPushButton, \
    QHBoxLayout, QSpacerItem, QSizePolicy, QTextBrowser
from UI.Util.SettingDialog import SettingDialog
from res.resource_rc import *
from Config.Config import config, CatchExceptions

# AddWidget
from PyQt5.QtGui import QFont
from PyQt5.QtCore import Qt, pyqtSignal, QMetaObject, QCoreApplication
from PyQt5.QtWidgets import QWidget, QGridLayout, QLabel,  QPushButton, QVBoxLayout, QHBoxLayout, QLineEdit, QMessageBox
from Tools.Util import *
from Config.Config import config, CatchExceptions

# FundMainWin
import os
from PyQt5.QtCore import QMetaObject, QCoreApplication, Qt, pyqtSignal
from PyQt5.QtGui import QPainter, QPen, QColor, QPixmap
from PyQt5.QtWidgets import QWidget, QGridLayout, QTabWidget, QMessageBox, QLineEdit, QPushButton, QSizePolicy, QSpacerItem, QSplitter
from UI.Table.MyTableView import MyTableView
from UI.Table.SelfSelectionTableView import SelfSelectionTableView
from Config.Config import Version
from Tools.Util import *
from threading import Thread

# LoadWidget
import os
import sys
import time
from threading import Thread
from PyQt5.QtGui import QPainter, QPixmap
from PyQt5.QtCore import Qt, QPoint, pyqtSignal
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtWidgets import QWidget, QApplication, QMessageBox
from UI.AccurateWidget import AccurateWidget
from Tools.Util import *
from res.resource_rc import *
from apscheduler.schedulers.blocking import BlockingScheduler
from Config.Config import config, CatchExceptions

# LoginDialog
import os
import sys
import random
import time
from threading import Thread
from PyQt5.QtCore import Qt, pyqtSignal, QEvent, QSize
from PyQt5.QtGui import QFont, QIcon, QMovie
from PyQt5.QtWidgets import QWidget, QGridLayout, QApplication, QLabel, QPushButton, \
    QHBoxLayout, QSpacerItem, QSizePolicy, QDialog, QCheckBox, QLineEdit, QMessageBox, QVBoxLayout
from res.resource_rc import *
from UI.Login.LoginLeftWid import LoginLeftWid
from Config.Config import config, CatchExceptions
from UI.LoadWidget import LoadWidget

# LoginLeftWid
import os
import sys
from PyQt5.QtCore import Qt, QSize, QCoreApplication
from PyQt5.QtWidgets import QWidget, QGridLayout, QVBoxLayout, QPushButton, QLabel, QSpacerItem, QSizePolicy
from PyQt5.QtGui import QPainter, QPen, QColor, QPixmap, QIcon, QFont
from res.resource_rc import *

# MyTableView
import typing
from PyQt5.QtCore import QItemSelectionModel, pyqtSignal, Qt, QModelIndex
from PyQt5.QtGui import QStandardItemModel, QStandardItem, QBrush, QColor, QFont, QCursor
from PyQt5.QtWidgets import QTableView, QAbstractItemView, QItemDelegate, QHeaderView, QAbstractSlider, QMenu, QAction, QMessageBox
from Tools.Util import *
from threading import Thread
from math import ceil
from UI.Curve.YieldRateDialog import YieldRateDialog
import os
import json
from Config.Config import config, CatchExceptions

# SelfSelectionTableView
from PyQt5.QtCore import QItemSelectionModel, pyqtSignal, Qt, QModelIndex
from PyQt5.QtGui import QStandardItemModel, QStandardItem, QBrush, QColor, QFont, QCursor
from PyQt5.QtWidgets import QTableView, QAbstractItemView, QItemDelegate, QMessageBox, QAbstractSlider, QMenu, QAction
from Tools.Util import *
from threading import Thread
from UI.Curve.YieldRateDialog import YieldRateDialog
import json
from Config.Config import config, CatchExceptions

# SettingDialog
import sys
from threading import Thread
from PyQt5.QtGui import QGuiApplication, QPixmap, QFont
from PyQt5.QtCore import Qt, pyqtSignal, QRect, QMetaObject, QCoreApplication, QPoint, QEvent
from PyQt5.QtWidgets import QWidget, QGridLayout, QApplication, QLabel,  QPushButton, QFrame, QMessageBox, QPlainTextEdit,\
    QDialog, QTabWidget, QVBoxLayout, QHBoxLayout, QGroupBox, QCheckBox, QLineEdit, QSizePolicy, QSpacerItem, QScrollArea
from UI.Util.AddWidget import AddWidget
from Config.Config import config, CatchExceptions
from Tools.Util import set_shortcut
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.schedulers.base import STATE_RUNNING
from res.resource_rc import *
import webbrowser
import copy

# UpgradeMessage
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtCore import pyqtSignal, QUrl
from PyQt5.QtGui import QDesktopServices
from threading import Thread
from threading import RLock
import time

# YieldRateDialog
from PyQt5.QtChart import QChart, QLineSeries, QValueAxis, QChartView, QDateTimeAxis
import datetime
import time
import sys
from PyQt5.QtCore import Qt, QRect, QDateTime, QDate, QPoint, QPointF, pyqtSignal
from PyQt5.QtGui import QPainter, QCursor, QColor, QBrush, QMouseEvent
from PyQt5.QtWidgets import QToolTip, QWidget, QApplication, QGridLayout, QGraphicsSimpleTextItem

# AccurateCurveDialog
from PyQt5.QtChart import QChart, QLineSeries, QValueAxis, QChartView, QDateTimeAxis
import datetime
import time
import sys, os
from PyQt5.QtCore import Qt, QRect, QDateTime, QDate, QPoint, QPointF, pyqtSignal, QEvent
from PyQt5.QtGui import QPainter, QCursor, QColor, QBrush, QMouseEvent, QIcon
from PyQt5.QtWidgets import QToolTip, QWidget, QApplication, QGridLayout, QGraphicsSimpleTextItem, \
                            QPushButton, QSpacerItem, QSizePolicy, QMenu, QAction, QDialog
from res.resource_rc import *
from Config.Config import CatchExceptions

# StartLoadForm
import sys
import time
import threading
from PyQt5.QtGui import QPainter, QPixmap
from PyQt5.QtWidgets import QWidget, QApplication
from PyQt5.QtCore import pyqtSignal, Qt
from res.resource_rc import *

# UtilWidget
import time
import random
from Tools.Util import *
from threading import Thread
from PyQt5.QtGui import QGuiApplication, QPixmap, QFont
from PyQt5.QtCore import Qt, pyqtSignal, QRect, QCoreApplication, QFile, QIODevice
from PyQt5.QtWidgets import QWidget, QGridLayout, QHBoxLayout, QGroupBox, QScrollArea, QSizePolicy, QSpacerItem, QTextBrowser
from UI.Util.DaPanUnit import DaPanUnit
from UI.Util.ToolBtn import *
from UI.AccountBook.AccountBookDialog import AccountBookDialog
from Config.Config import CatchExceptions
from res.resource_rc import *

# DaPanUnit
from PyQt5.QtCore import Qt, pyqtSignal, QCoreApplication
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import QLabel, QWidget, QGridLayout
from Config.Config import CatchExceptions

# ToolBtn
from PyQt5.QtCore import Qt, pyqtSignal, QSize
from PyQt5.QtGui import QMovie, QMouseEvent
from PyQt5.QtWidgets import QFrame, QGridLayout, QLabel, QMessageBox

# DetailsDialog
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt, QRect
from PyQt5.QtWidgets import QGroupBox, QGridLayout, QVBoxLayout, QScrollArea, QWidget, QDialog
from res.resource_rc import *
from Config.Config import config, CatchExceptions
from UI.Curve.AccChart import AccChart

# AccDia
import time
import sys, os
from datetime import datetime
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt, QRect, QDate, pyqtSignal, QEvent, QTime, QMetaObject
from PyQt5.QtWidgets import QGroupBox, QGridLayout, QVBoxLayout, QScrollArea, QWidget, \
                            QPushButton, QSpacerItem, QSizePolicy, QHBoxLayout, QLabel, QDialog, QApplication
from res.resource_rc import *
from Config.Config import config, CatchExceptions
from UI.AccountBook.AccountBookDialog import AccountBookDialog
from UI.AccountBook.AccountUnit import AccountUnit

# AccChart
from datetime import datetime
import time
import sys, os
from PyQt5.QtCore import Qt, QRect, QDateTime, QDate, QPoint, QPointF, pyqtSignal, QEvent
from PyQt5.QtGui import QPainter, QCursor, QColor, QBrush, QMouseEvent, QIcon
from PyQt5.QtWidgets import QToolTip, QWidget, QApplication, QGridLayout, QGraphicsScene, \
    QGraphicsView, QSpacerItem, QSizePolicy, QMenu, QAction
from PyQt5.QtChart import QChart, QChartView, QBarSeries, QBarSet, QBarCategoryAxis, QValueAxis, QLineSeries, QAbstractBarSeries
from res.resource_rc import *
from Config.Config import CatchExceptions

# AccountBookDialog
import time
import sys, os
from datetime import datetime
from PyQt5.QtCore import Qt, QDateTime, QDate, pyqtSignal, QEvent, QTime, QMetaObject, QCoreApplication
from PyQt5.QtWidgets import QCheckBox, QDateEdit, QApplication, QGridLayout, QLineEdit, QMessageBox, \
                            QPushButton, QSpacerItem, QSizePolicy, QHBoxLayout, QLabel, QDialog, QComboBox
from res.resource_rc import *
from Config.Config import config, CatchExceptions

# AccountUnit
from datetime import datetime
import time
import sys, os
from threading import Thread
from PyQt5.QtCore import Qt, pyqtSignal, QEvent, QMetaObject, QCoreApplication
from PyQt5.QtWidgets import QApplication, QGridLayout, QPushButton, QLabel, QFrame, QMessageBox
from res.resource_rc import *
from Config.Config import CatchExceptions
from Tools.Util import *
from UI.AccountBook.AccountBookDialog import AccountBookDialog
from UI.AccountBook.DetailsDialog import DetailsDialog

# Analysis
import requests
from pyecharts import options as opts
from pyecharts.globals import ThemeType
from pyecharts.charts import Bar
from pyecharts.charts import Pie
import json
import os

# MonthDataCurve
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPainter, QCursor, QColor
from PyQt5.QtWidgets import QToolTip, QDialog, QApplication, QGridLayout
from PyQt5.QtChart import QChart, QChartView, QBarSeries, QBarSet, QBarCategoryAxis, QValueAxis
from res.resource_rc import *
from Tools.Util import *
from Config.Config import CatchExceptions

# HoldingPie
import sys
import random
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPainter, QColor, QCursor
from PyQt5.QtWidgets import QToolTip, QDialog, QApplication, QGridLayout
from PyQt5.QtChart import QChart, QChartView, QPieSeries, QPieSlice
from Tools.Util import *
from res.resource_rc import *
from Config.Config import CatchExceptions

# FundCompany
import os
import re
import copy
import requests
from enum import Enum
from lxml import etree
from datetime import datetime
from multiprocessing import Pool
from urllib.request import urlcleanup

# AutoWechat
import pyautogui
import time
import pyperclip
import json
from PyQt5.QtGui import QImage
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.tbp.v20190627 import tbp_client, models

from Config.Config import *
from Tools.DBTool import *
from Tools.Util import *
from Tools.Analysis import *
from Tools.fcntlock import *
from Tools.FundCompany import *
from UI.LoadWidget import *
from UI.Login.LoginDialog import *
from UI.Login.LoginLeftWid import *
from UI.Util.AddWidget import *
from UI.Util.SettingDialog import *
from UI.Table.SelfSelectionTableView import *
from UI.AccurateWidget import *
from UI.Table.FundMainWin import *
from UI.Table.MyTableView import *
from UI.Util.UpgradeMessage import *
from UI.Curve.YieldRateDialog import *
from UI.Curve.AccurateCurveDialog import *
from UI.Login.StartLoadForm import *
from UI.Util.UtilWidget import *
from UI.Util.DaPanUnit import *
from UI.Util.ToolBtn import *
from UI.AccountBook.DetailsDialog import *
from UI.AccountBook.AccDia import *
from UI.Curve.AccChart import *
from UI.AccountBook.AccountBookDialog import *
from UI.AccountBook.AccountUnit import *
from UI.Curve.MonthDataCurve import *
from UI.Curve.HoldingPie import *

from Tools.AutoWechat import *


def close():
    sys.exit(1)

def isConnected():
    try:
        requests.get("http://www.baidu.com", timeout=2)
    except:
        return False
    return True

def main():
    # 锁定程序，只能开启一个进程

    try:
        f = fcntl.lock()
        atexit.register(fcntl.unlock, f)
    except:
        raise Exception('小伙子，你在干什么？只允许打开一个软件！')

    try:
        # if not 'base_library' in sys.path[0]:
        #     ReBuildResources()  # 重构资源文件
        url = QUrl('http://www.zhigen.cool')
        url.query()
        extra()
    except:
        print('Build阶段重构资源文件失败，Release阶段不需要重构')

    QApplication.setAttribute(Qt.AA_UseOpenGLES | Qt.AA_EnableHighDpiScaling)
    app = QApplication(sys.argv)

    startLoadForm = StartLoadForm()
    startLoadForm.show()
    QApplication.processEvents()

    new = Ui_FundMainWin()
    try:
        #  判断网络
        if not isConnected():
            startLoadForm.close()
            QApplication.processEvents()
            QMessageBox.critical(new, '当前设备未联网', '当前设备未联网，请连接网络后重试！')
            sys.exit(-1)

        QApplication.setStyle(QStyleFactory.create("Fusion"))
        app.setWindowIcon(QIcon(':/Img/curve1.ico'))
        app.setQuitOnLastWindowClosed(False)  # 解决关闭子窗口时整个程序都会一起退出的问题
        font = QFont("Arial,SimSun", 9)
        app.setFont(font)

        assfile = ':/Stylesheet/Win.qss'
        qssFile = QFile(assfile)
        qssFile.open(QIODevice.OpenModeFlag.ReadOnly)
        if qssFile.isOpen():
            qss = str(qssFile.readAll(), encoding='utf-8')
            app.setStyleSheet(qss)
            qssFile.close()

        hasNewVersion, url, forcedUpdating = config.checkNewVersion()
        if hasNewVersion:
            msgBox = QMessageBox(new)
            msgBox.setIcon(QMessageBox.Icon.Information)
            msgBox.setWindowTitle('检测到新版本')
            msgBox.setText('检测到新版本，为了您更好的体验，请前往更新！')
            msgBox.addButton(QMessageBox.Yes)
            msgBox.button(QMessageBox.Yes).setText('前往更新')
            if forcedUpdating:
                pass
            else:
                msgBox.addButton(QMessageBox.No)
                msgBox.button(QMessageBox.No).setText('暂不更新')
            startLoadForm.close()
            QApplication.processEvents()
            msgBox.exec()
            startLoadForm.show()
            QApplication.processEvents()
            if msgBox.clickedButton() == msgBox.button(QMessageBox.Yes):
                webbrowser.open(url)
                time.sleep(1)
                sys.exit(1)

        settingDialog = None
        loginDialog = LoginDialog()
        config.getSetting()
        if int(config.settings.get('allowLogin', '0')) == 0:
            startLoadForm.close()
            QApplication.processEvents()
            # QMessageBox.warning(loginDialog, '警告', '系统正在维护中...')
            sys.exit(-1)

        if int(config.settings.get('needLogin', '0')) == 1:
            startLoadForm.close()
            QApplication.processEvents()
            loginDialog.exec()
            settingDialog = loginDialog.getSettingDialog()
            startLoadForm.show()
            QApplication.processEvents()
        else:
            # 用户协议
            if not config.getUserRole():
                msgBox = QMessageBox(loginDialog)
                msgBox.setIcon(QMessageBox.Icon.Warning)
                msgBox.setWindowTitle('用户协议')
                msgBox.setText('1、基金有风险，投资需谨慎，您的一切操作与本软件无关，请谨慎操作！\n'
                               '2、本软件获取的所有基金数据均为使用者自行获取，任何后果与软件开发者无关！\n'
                               '3、本软件作者未授权任何个人或组织使用本软件内数据获取利益，任何后果与软件开发者无关！\n'
                               '4、本软件完全免费，不会向使用者强行索取任何费用！任何倒买倒卖此软件人员与开发者无关！\n'
                               '5、本软件安全无毒，若杀毒软件报毒，请使用者自行斟酌是否使用！\n'
                               '6、当您使用本软件起，即默认您已同意承担所有投资风险，任何后果与软件开发者无关！\n'
                               '7、最终解释权归软件开发者所有！')
                msgBox.addButton(QMessageBox.Yes)
                msgBox.button(QMessageBox.Yes).setText('同意')
                msgBox.addButton(QMessageBox.No)
                msgBox.button(QMessageBox.No).setText('不同意')
                startLoadForm.close()
                QApplication.processEvents()
                msgBox.exec()

                if msgBox.clickedButton() == msgBox.button(QMessageBox.Yes):
                    config.setUserRole(True)
                    startLoadForm.show()
                    QApplication.processEvents()
                else:
                    config.setUserRole(False)
                    sys.exit(-1)

            dbName, dbPw, dbRc, dbFc, dbIp, dbAl, checkRobot = config.loginWithNoUI()
            if not dbAl:
                startLoadForm.close()
                QApplication.processEvents()
                QMessageBox.warning(loginDialog, '警告', '该账号已被限制登陆！')
                sys.exit(-1)
            if not checkRobot:
                startLoadForm.close()
                QApplication.processEvents()
                QMessageBox.warning(loginDialog, '警告', '该电脑已被限制登陆！')
                sys.exit(-1)

            loadWidget = LoadWidget(new)
            new.fundSateChangedSignal.connect(loadWidget.onFundSateChanged)
            loadWidget.show()
            loadWidget.onLogin()
            settingDialog = loadWidget.getSettingDialog()

        # # 检查新版本
        # dbs = DBSession()
        # if not UpgradeMessage(new, dbs).checkVersion():
        #     # 检查推送信息
        #     UpgradeMessage(new, dbs).checkNotification()

        # new.show()  # 主界面不显示
        new.setSettingDialog(settingDialog)
        startLoadForm.closeThread()
        weChat.run()
        sys.exit(app.exec())
    except Exception as e:
        QMessageBox.critical(new, 'Critical question happened', str(e))
        exit(-1)

if __name__ == '__main__':
    main()